package org.example.springbook.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.example.springbook.contants.Contants;
import org.example.springbook.model.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 在方法执行前进行拦截，每个方法在执行前都会执行下面的方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //这里进行登录验证
        log.info("目标方法执行前执行: LoginInterceptor.preHandle.... ");
        HttpSession session = request.getSession();
        UserInfo userInfo=(UserInfo) session.getAttribute(Contants.USER_SESSION_KEY);
        if(userInfo==null || userInfo.getId()<1){
            //401代表没有身份，也就是noauthed
            //这里是服务端进行返回的状态码，跟我们在服务层返回的业务状态码没有关系。
            //只有当程序能够顺利的进来的时候，才会返回我们所设定业务状态码
            response.setStatus(401);
            return false;
        }
        return true;
    }

    /**
     * 在方法执行后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //这一般是指在最后的时候进行渲染图形化界面
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
